<!-- 编辑动态页面 -->
<template>
    <div class="EditDynamics">
        <van-sticky :offset-top="0">
            <van-nav-bar title="发表动态" left-text="返回" @click-left="clickLeft">
                <template #right> 
                    <van-button type="primary" size="small" :disabled="disabled" @click="release">发表</van-button>
                </template>
            </van-nav-bar>
        </van-sticky>
        <van-field rows="2" autosize type="textarea" maxlength="50" placeholder="发点什么吧..." clearable show-word-limit v-model="str" />
        <van-uploader v-model="imgList" multiple :max-count="9" :before-delete="beforeDelete" />
    </div>
</template>

<script>
    import Uppy from '@uppy/core';
    import XHR from "@uppy/xhr-upload";
    import { mapActions, mapState } from 'vuex';
    import { Toast, Dialog } from "vant";

    export default {
        name: "EditDynamicsView",
        data() {
            return {
                str: "",
                imgList: [],
            }
        },
        computed: {
            ...mapState(["user"]),
            disabled() {    // 如果有图片或者文字那么可以发布动态解锁发布按钮
                if (this.str != "" || this.imgList.length > 0)
                    return false
                else
                    return true
            },
            uppy() {
                return new Uppy({
                    autoProceed: false,                             // 是否自动上传
                    restrictions: {
                        maxNumberOfFiles: 6,                        // 设置最大上传文件数量
                        allowedFileTypes: ['.jpg', '.jpeg', '.png'] // 设置允许的文件类型
                    }
                })
                .use(XHR, { 
                    endpoint: 'http://localhost:4000/api/editDynamics/upload',  // 上传地址
                    formData: true,                                             // 启用FormData发送数据
                    fieldName: 'file',                                          // 文件字段名称
                    allowedMetaFields: ['userPhone', 'date', 'text']            // 添加额外的元数据字段 
                });
            }
        },
        watch: {
            imgList(to, from) { // 监听图片列表，用户有上传图片就上传
                if (to.length == from.length || to.length < from.length) {   // 如果删除图片就不上传
                    return;
                }

                // 将ui变成上传中
                this.imgList.at(-1).message = "上传中...";
                this.imgList.at(-1).status = "uploading";

                // 设置额外的元数据字段，服务器保存要使用这些数据
                this.uppy.setMeta({
                    userPhone: this.user.phone,
                    date: Date.now(),
                });

                // 添加文件到上传队列
                this.uppy.addFile({
                    source: 'file input',
                    name: this.imgList.at(-1).file.name,
                    type: this.imgList.at(-1).file.type,
                    data: this.imgList.at(-1).file,
                });

                //  开始上传
                this.uppy.upload()
                .then(result => {
                    const response = result.successful[0].response.body;
                    // 将ui变成上传成功
                    this.imgList.at(-1).message = "";
                    this.imgList.at(-1).status = "";
                    this.imgList.at(-1).url = response.url;

                    this.uppy.clear() // 清空上传队列

                    if (result.failed.length > 0) {
                        result.failed.forEach(file => console.error(file.error));
                    }
                })
                .catch((error) => {
                    console.error('上传过程中发生错误:', error);
                    this.imgList.at(-1)[length].message = "failed";
                    this.imgList.at(-1)[length].status = "上传失败";
                }); 
            }
        },
        methods: {
            ...mapActions('editDynamic', ['deleteDynamicImageFile', 'releaseDynamic']),
            async release() {
                let res = await this.releaseDynamic({ 
                    phone: this.user.phone, 
                    text: this.str,
                    time: Date.now(), 
                });

                Toast.clear();

                if (res.error) {
                    Toast.fail(`发布失败: ${ res.error }`);
                }
                else {
                    Toast.success('发布成功');
                    this.$router.back(-1);
                }
            },
            async beforeDelete(file, detail) {
                let res = await this.deleteDynamicImageFile({ 
                    index: detail.index, 
                    phone: this.user.phone, 
                    code: 1     // 1 代表删除一个动态图片
                });

                if (res.error) {
                    Toast.fail(`删除失败: ${ res.error }`);
                }
                else {
                    Toast.success('删除成功');
                    this.imgList.splice(detail.index, 1);
                }
            },
            clickLeft() {
                if (this.str == "" && this.imgList.length == 0) {
                    this.$router.back(-1);
                    return;
                }
                
                Dialog.confirm({ 
                    message: '是否保存草稿',
                    confirmButtonText: '保存',
                    cancelButtonText: '不保存',
                 })
                .then(() => this.$router.back(-1))
                .catch(async () => {
                    this.$router.back(-1);

                    let res = await this.deleteDynamicImageFile({ 
                        index: null, 
                        phone: this.user.phone, 
                        code: 0     // 0 代表删除所有动态图片
                    });

                    if (res.error) {
                        Toast.fail(`删除失败: ${ res.error }`);
                    }
                    else {
                        this.imgList = [];
                    }
                });
            }
        },
    }
</script>

<style lang="less" scoped>
</style>